package kube

import (
	"errors"
	"fmt"
	"github.com/spf13/cobra"
	"io/ioutil"
	"strings"
)

func init() {
	registerSubCmd(stepCmd())
}

func stepCmd() *cobra.Command {
	supportSteps := "prepare,etcd,container,master,node,network"

	var cmd = &cobra.Command{
		Use:   "step",
		Short: "执行创建集群的某些步骤",
		Long: `执行创建集群的某些步骤
支持 prepare etcd container master node network
prepare: 服务器环境准备，安装chrony、ipset、ipvsadm、nfs-utils等基础软件，还有分发证书功能
etcd: 安装etcd服务
container: 安装容器服务，支持docker和containerd
master: 部署和运行kube-apiserver、kube-controller-manager、kube-scheduler、kubelet、kube-proxy服务
node: 部署和运行kubelet、kube-proxy服务
network: 支持安装calico、cilium、flannel、kube-router、kube-ovn
`,
		Example: `opsctl kb step prepare #只执行环境初始化  
opsctl kb step etcd container #执行etcd和container两步  
`,
		Args: func(cmd *cobra.Command, args []string) error {
			if len(args) == 0 {
				return fmt.Errorf("请指定要操作的步骤")
			}

			for _, arg := range args {
				if !strings.Contains(supportSteps, arg) {
					return fmt.Errorf("仅支持%s 输入步骤%s不支持", supportSteps, arg)
				}
			}

			return nil
		},
		RunE: func(cmd *cobra.Command, args []string) error {

			fileInfos, err := ioutil.ReadDir(kubeConfig.Dir)

			if err != nil {
				return errors.New("读取ansible目录" + kubeConfig.Dir + "文件错误")
			}

			playbooks := make([]string, 0, 8)
			for _, step := range args {
				for _, fileInfo := range fileInfos {
					if strings.Contains(fileInfo.Name(), step) {
						playbooks = append(playbooks, fileInfo.Name())
					}
				}
			}

			return newAnsiblePlaybookAndRun(playbooks...)

		},
	}

	return cmd
}
